﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Web;
using System.Security.Cryptography;
using System.Text.RegularExpressions;
using System.Text;
using System.Net;
using System.IO;
using System.Management;
//using HMS;

#region << 版 本 信 息 >>
/****************************************************
* 文 件 名：MethodCls.cs
* Copyright(c) 2015-08-26 IT刀客（邢全政）
* CLR 版本: 4.0.30319.235 
* 创 建 人：IT刀客
* 创建日期：2015-08-26 15:01:07
*******************************************************/
#endregion
/// <summary>
/// MethodCls类为各种封装的方法
/// </summary>
public class MethodCls
{
    private static string constr = ConfigurationManager.AppSettings["con"]; //连接数据库
	public MethodCls()
	{
		//
		// TODO: 在此处添加构造函数逻辑
		//
	}
    /// <summary>
    /// 产生随机数方法:minValue目标随机数最小数；maxValue随机数最大数;count随机数个数;
    /// </summary>
    /// <param name="minValue"> minValue随机数最小数;</param>
    /// <param name="maxValue">maxValue随机数最大数;</param>
    /// <param name="count">count随机数个数;</param>
    /// <returns>返回指定长度随机数</returns>
    public static int GetRandom(int minValue, int maxValue, int count)
    {
        Random rnd = new Random();
        int length = maxValue - minValue + 1;
        byte[] keys = new byte[length];
        rnd.NextBytes(keys);
        int[] items = new int[length];
        for (int i = 0; i < length; i++)
        {
            items[i] = i + minValue;
        }
        Array.Sort(keys, items);
        int[] result = new int[count];
        Array.Copy(items, result, count);
        string singleNum = "";
        for (int i = 0; i < result.Length; i++)
        {
            singleNum += result[i].ToString();
        }
        if (singleNum.Length<6)
        {
            singleNum += "1";
        }
        return int.Parse(singleNum);
    }
    /// <summary>
    /// MD5字符串加密方法，传入要加密的字符串str
    /// </summary>
    public static string MD5(string str)
    {
        //获取填充字节448
        byte[] result = Encoding.UTF8.GetBytes(str);
        MD5 md5 = new MD5CryptoServiceProvider();
        byte[] output = md5.ComputeHash(result);
        string md5Str = BitConverter.ToString(output).Replace("-", ""); 
        return md5Str;
    }
    /// <summary>
    /// 时间戳生成方法
    /// </summary>
    public static string stampTime()
    {
        TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
        return Convert.ToInt64(ts.TotalSeconds).ToString();  
    }
    ///<summary>
    /// RFC1867协议文件上传方法
    /// </summary>
    public static string RfcHttpPost(string url, string[] keyNames, string[] fileName)
    {
        string res = string.Empty;
        if(keyNames.Length>0)
        {
            for(int i=0;i< keyNames.Length;i++)
            {
                if(i== keyNames.Length-1)
                {
                    break;
                }
                #region///开始处理上传文件/数据参数流
                try
                {
                    //按照rfc1867协议标准封送文件
                    FileInfo guest = new FileInfo(fileName[i]);
                    FileInfo photo = new FileInfo(fileName[i+1]);
                    byte[] btTxt = new Byte[checked((uint)Math.Min(4096, guest.Length))];
                    byte[] btpic = new Byte[checked((uint)Math.Min(4096, photo.Length))];

                    string boundary = "------------" + DateTime.Now.Ticks.ToString("x");// 分隔符
                    // 旅客身份信息文本文件上传的http请求头
                    HttpWebRequest req = WebRequest.Create(url) as HttpWebRequest;
                    req.Method = "POST";
                    req.ContentType = "multipart/form-data; boundary=" + boundary;
                    req.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8";
                    req.KeepAlive = true;
                    req.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.57 Safari/537.36";

                    //组织表单数据--身份信息
                    StringBuilder sbGuest = new StringBuilder();
                    sbGuest = sbGuest.Append("--"+boundary+ "\r\n");
                    sbGuest = sbGuest.Append("Content-Disposition:form-data; name=\"" + "guest" + "\"; filename=\"" + guest + "\"\r\n");
                    sbGuest = sbGuest.Append("Content-Type:text/plain\r\n\r\n");
                    byte[] start_data_guest = Encoding.Unicode.GetBytes(sbGuest.ToString());
                    //旅客照片数据头文件
                    StringBuilder sbPhoto = new StringBuilder();
                    sbGuest = sbPhoto.Append("--"+boundary+ "\r\n");
                    sbGuest = sbPhoto.Append("Content-Disposition:form-data; name=\"" + "photo" + "\"; filename=\"" + photo + "\"\r\nContent-Type:image/jpeg\r\n\r\n");
                    byte[] start_data_photo = Encoding.Unicode.GetBytes(sbPhoto.ToString());
                    //http请求结尾
                    byte[] end_data = Encoding.Unicode.GetBytes("\r\n--" + boundary + "--\r\n");

                    //计算报文长度
                    req.ContentLength = start_data_guest.Length + start_data_photo.Length + btTxt.Length + btpic.Length
                            + end_data.Length;
                    Stream rs = req.GetRequestStream();
                    //封送参数到接口url
                    rs.Write(start_data_guest, 0, start_data_guest.Length);
                    rs.Write(btTxt, 0, btTxt.Length);
                    rs.Write(start_data_photo, 0, start_data_photo.Length);

                    rs.Write(btpic, 0, btpic.Length);
                    rs.Write(end_data, 0, end_data.Length);
 
                    WebResponse wResponse = req.GetResponse();
                    Stream stream = wResponse.GetResponseStream();
                    StreamReader reader = new StreamReader(stream, Encoding.UTF8);
                    res = reader.ReadToEnd().Trim();   //获取被调用的url上的返回值  
                    req.GetRequestStream().Close();
                    reader.Close();
                    if (wResponse != null)
                    {
                        wResponse.Close();
                        wResponse = null;
                    }
                    if (req != null)
                    {
                        req = null;
                    }
                }
                catch (Exception ex)
                {
                    return ("服务器未响应：" + ex.Message);
                }
                #endregion
            }
        } 
        return res;
    }
    ///<summary>
    ///HTTP调用
    ///</summary>
    public static string httpPost(string url,string pData)
    {
        pData = get_uft8(pData);
        //读取返回消息
        string res = string.Empty;
        try
        {
            HttpWebRequest wRequest = WebRequest.Create(url) as HttpWebRequest; 
            wRequest.Method = "POST";
            byte[] buffer = Encoding.UTF8.GetBytes(pData);

            wRequest.ContentLength = buffer.Length;
            wRequest.ContentType = "application/x-www-form-urlencoded";
            wRequest.GetRequestStream().Write(buffer, 0, buffer.Length);

            WebResponse wResponse = wRequest.GetResponse();  
            Stream stream = wResponse.GetResponseStream();
            StreamReader reader = new StreamReader(stream,Encoding.UTF8);
            res = reader.ReadToEnd();   //获取被调用的url上的返回值  
            reader.Close();
        }
        catch (Exception ex)
        {
            return ("服务器未响应：" + ex.Message);
        }
        return res;
    }
    ///<summary>
    ///字符串转换为UTF8编码
    ///</summary>
    public static string get_uft8(string unicodeString)
    {
        UTF8Encoding utf8 = new UTF8Encoding();
        Byte[] encodedBytes = utf8.GetBytes(unicodeString);
        String decodedString = utf8.GetString(encodedBytes);
        return decodedString;
    }

    /// <summary>   
    /// 获取中文串对应的首字母字符串   
    /// </summary>   
    /// <param name="Cnstr">中文串</param>   
    /// <returns>中文串对应的首字母英文串</returns>   
    public static string GetSpellCode(string Cnstr)
    {
        string temp = "";
        for (int i = 0; i < Cnstr.Length; i++)
        {

            temp += GetSpellCodeAt(Cnstr.Substring(i, 1));
        }
        return temp;
    }

    public static string GetSpellCodeAt(string s)
    {
        long iCnChar;

        byte[] ZW = System.Text.Encoding.Default.GetBytes(s);
        if (ZW.Length == 1)
        {
            return s.ToUpper();
        }

        int i1 = (short)ZW[0];
        int i2 = (short)ZW[1];
        iCnChar = i1 * 256 + i2;

        if ((iCnChar >= 45217) && (iCnChar <= 45252))
        {
            return "A";
        }
        else if ((iCnChar >= 45253) && (iCnChar <= 45760))
        {
            return "B";
        }
        else if ((iCnChar >= 45761) && (iCnChar <= 46317))
        {
            return "C";
        }
        else if ((iCnChar >= 46318) && (iCnChar <= 46825))
        {
            return "D";
        }
        else if ((iCnChar >= 46826) && (iCnChar <= 47009))
        {
            return "E";
        }
        else if ((iCnChar >= 47010) && (iCnChar <= 47296))
        {
            return "F";
        }
        else if ((iCnChar >= 47297) && (iCnChar <= 47613))
        {
            return "G";
        }
        else if ((iCnChar >= 47614) && (iCnChar <= 48118))
        {
            return "H";
        }
        else if ((iCnChar >= 48119) && (iCnChar <= 49061))
        {
            return "J";
        }
        else if ((iCnChar >= 49062) && (iCnChar <= 49323))
        {
            return "K";
        }
        else if ((iCnChar >= 49324) && (iCnChar <= 49895))
        {
            return "L";
        }
        else if ((iCnChar >= 49896) && (iCnChar <= 50370))
        {
            return "M";
        }

        else if ((iCnChar >= 50371) && (iCnChar <= 50613))
        {
            return "N";
        }
        else if ((iCnChar >= 50614) && (iCnChar <= 50621))
        {
            return "O";
        }
        else if ((iCnChar >= 50622) && (iCnChar <= 50905))
        {
            return "P";
        }
        else if ((iCnChar >= 50906) && (iCnChar <= .51386))
        {
            return "Q";
        }
        else if ((iCnChar >= 51387) && (iCnChar <= 51445))
        {
            return "R";
        }
        else if ((iCnChar >= 51446) && (iCnChar <= 52217))
        {
            return "S";
        }
        else if ((iCnChar >= 52218) && (iCnChar <= 52697))
        {
            return "T";
        }
        else if ((iCnChar >= 52698) && (iCnChar <= 52979))
        {
            return "W";
        }
        else if ((iCnChar >= 52980) && (iCnChar <= 53640))
        {
            return "X";
        }
        else if ((iCnChar >= 53689) && (iCnChar <= 54480))
        {
            return "Y";
        }
        else if ((iCnChar >= 54481) && (iCnChar <= 55289))
        {
            return "Z";
        }
        else return ("?");
    }
    ///<summary> 
    ///生成订单号
    ///<param name="UserName">用户名</param>  
    ///</summary> 
    /// <returns>返回订单号字符串</returns>
    public static string OrderNo(string UserName)
    {
        string OrderSn = "";
        string Param = "";
        SqlParameter[] sp = {new SqlParameter("@UserName",UserName)};
        DataTable dt  = SqlHelper.ExecuteProcDataSet(constr, CommandType.StoredProcedure, "getExistsOrderParam", sp).Tables[0];
        string CountP = dt.Rows[0]["Result"].ToString();
        string UserId = dt.Rows[0]["UserId"].ToString();
        UserId = UserId.PadLeft(3, '0');
        if (CountP == "-1")
        {
            //当日不存在订单
            string OdrNo = DateTime.Now.ToString("yyyyMMdd") +UserId+ "001";  //
            Param = "1";
            OrderSn = OdrNo + "," + Param;
        }
        else
        {
            Param = (int.Parse(CountP.ToString())+1).ToString();//获取数据库订单中的参数尾数
            Param = Param.PadLeft(3, '0');
            OrderSn = DateTime.Now.ToString("yyyyMMdd") + UserId + Param;
            OrderSn = OrderSn + "," + Param.Remove(0, 2);
        }
        return OrderSn;
    }

    /// <summary>
    /// 判断输入的字符串是否是一个合法的手机号
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    public static bool IsMobilePhone(string input)
    {
        Regex regex = new Regex("^13\\d{9}$");//至判断13开头
        return regex.IsMatch(input);
    }

    /// <summary>
    /// 判断输入的字符串只包含数字
    /// 可以匹配整数和浮点数
    /// ^-?\d+$|^(-?\d+)(\.\d+)?$
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    public static bool IsNumber(string input)
    {
        string pattern = "^-?\\d+$|^(-?\\d+)(\\.\\d+)?$";
        Regex regex = new Regex(pattern);
        return regex.IsMatch(input);
    }
    /// <summary>
    /// 匹配非负整数
    ///
    /// </summary>
   /// <param name="input"></param>
   /// <returns></returns>
    public static bool IsNotNagtive(string input)
    {
            Regex regex = new Regex(@"^\d+$");
        return regex.IsMatch(input);
    }
    /// <summary>
    /// 匹配正整数
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    public static bool IsUint(string input)
    {
        Regex regex = new Regex("^[0-9]*[1-9][0-9]*$");
        return regex.IsMatch(input);
    }
    /// <summary>
    /// 判断输入的字符串字包含英文字母
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    public static bool IsEnglisCh(string input)
    {
        Regex regex = new Regex("^[A-Za-z]+$");
        return regex.IsMatch(input);
    }

    /// <summary>
    /// 判断输入的字符串是否是一个合法的Email地址
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    public static bool IsEmail(string input)
    {
        string pattern = @"^([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$";
        Regex regex = new Regex(pattern);
        return regex.IsMatch(input);
    }

    /// <summary>
    /// 判断输入的字符串是否只包含数字和英文字母
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    public static bool IsNumAndEnCh(string input)
    {
        string pattern = @"^[A-Za-z0-9]+$";
        Regex regex = new Regex(pattern);
        return regex.IsMatch(input);
    }


    /// <summary>
    /// 判断输入的字符串是否是一个超链接
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    public static bool IsURL(string input)
    {
        //string pattern = @"http://([\w-]+\.)+[\w-]+(/[\w- ./?%&=]*)?";
        string pattern = @"^[a-zA-Z]+://(\w+(-\w+)*)(\.(\w+(-\w+)*))*(\?\S*)?$";
        Regex regex = new Regex(pattern);
        return regex.IsMatch(input);
    }

    /// <summary>
    /// 判断输入的字符串是否是表示一个IP地址
    /// </summary>
    /// <param name="input">被比较的字符串</param>
    /// <returns>是IP地址则为True</returns>
    public static bool IsIPv4(string input)
    {

        string[] IPs = input.Split('.');
        Regex regex = new Regex(@"^\d+$");
        for (int i = 0; i < IPs.Length; i++)
        {
            if (!regex.IsMatch(IPs[i]))
            {
                return false;
            }
            if (Convert.ToUInt16(IPs[i]) > 255)
            {
                return false;
            }
        }
        return true;
    }


    /// <summary>
    /// 计算字符串的字符长度，一个汉字字符将被计算为两个字符
    /// </summary>
    /// <param name="input">需要计算的字符串</param>
    /// <returns>返回字符串的长度</returns>
    public static int GetCount(string input)
    {
        return Regex.Replace(input, @"[\u4e00-\u9fa5/g]", "aa").Length;
    }

    /// <summary>
    /// 调用Regex中IsMatch函数实现一般的正则表达式匹配
    /// </summary>
    /// <param name="pattern">要匹配的正则表达式模式。</param>
    /// <param name="input">要搜索匹配项的字符串</param>
    /// <returns>如果正则表达式找到匹配项，则为 true；否则，为 false。</returns>
    public static bool IsMatch(string pattern, string input)
    {
        Regex regex = new Regex(pattern);
        return regex.IsMatch(input);
    }
    /// <summary>
    /// 从输入字符串中的第一个字符开始，用替换字符串替换指定的正则表达式模式的所有匹配项。
    /// </summary>
    /// <param name="pattern">模式字符串</param>
    /// <param name="input">输入字符串</param>
    /// <param name="replacement">用于替换的字符串</param>
    /// <returns>返回被替换后的结果</returns>
    public static string Replace(string pattern, string input, string replacement)
    {
        Regex regex = new Regex(pattern);
        return regex.Replace(input, replacement);
    }     
    /// <summary>
    /// 执行DataTable中的查询返回新的DataTable
    /// </summary>
    ///<param name="dt">传入要查找的源DataTable</param>
    ///<param name="conditions">传入的查询条件</param>
    public static DataTable getSelectDt(DataTable dt,string conditions)
    {
        DataTable newdt = new DataTable();
        newdt = dt.Clone(); // 克隆dt 的结构，包括所有 dt 架构和约束,并无数据；
        DataRow[] rows = dt.Select(conditions); // 从dt 中查询符合条件的记录；
        foreach (DataRow row in rows)  // 将查询的结果添加到dt中；
        {
            newdt.Rows.Add(row.ItemArray);
        }
        return newdt;
    }
    /// <summary>
    /// 给checkboxlist赋值
    /// </summary>
    /// <param name="checkList"></param>
    /// <param name="selval"></param>
    /// <param name="separator"></param>
    /// <returns></returns>
    public static string SetChecked(System.Web.UI.WebControls.CheckBoxList checkList, string selval, string separator)
    {
        selval = separator + selval + separator; //例如："0,1,1,2,1"->",0,1,1,2,1,"
        for (int i = 0; i < checkList.Items.Count; i++)
        {
            checkList.Items[i].Selected = false;
            string val = separator + checkList.Items[i].Value + separator;
            if (selval.IndexOf(val) != -1)
            {
                checkList.Items[i].Selected = true;
                selval = selval.Replace(val, separator); //然后从原来的值串中删除已经选中了的
                if (selval == separator) //selval的最后一项也被选中的话，此时经过Replace后，只会剩下一个分隔符
                {
                    selval += separator; //添加一个分隔符
                }
            }
        }
        selval = selval.Substring(1, selval.Length - 2); //除去前后加的分割符号
        return selval;
    }
    /// <summary>
    /// 得到CheckBoxList中选中的值
    /// </summary>
    /// <param name="checkList"></param>
    /// <param name="separator"></param>
    /// <returns></returns>
    public static string getcheck(System.Web.UI.WebControls.CheckBoxList checkList, string separator)
    {
        string selval = "";
        for (int i = 0; i < checkList.Items.Count; i++)
        {
            if (checkList.Items[i].Selected)
            {
                selval += "'" + checkList.Items[i].Value + "'" + separator;
            }
        }
        if (selval.Length > 1)
        {
            selval = selval.Substring(0, selval.Length - 1);
            selval = selval.Replace("'", "");
        }
        return selval;
    }
    //产生Token方法
    public static string getToken(string TimesTamp)
    {
        string sePre = "Qbird";//加密私钥前缀
        string seKey = "q$B%*(#d";//加密私钥
        string mStr = sePre + TimesTamp + seKey;
        string keyMd5 = MethodCls.MD5(mStr);
        return keyMd5;
    }
    /// <summary>
    /// 将json转换为DataTable
    /// </summary>
    /// <param name="strJson">得到的json</param>
    /// <returns></returns>
    public static DataTable JsonToDataTable(string strJson)
    {
        //转换json格式
        strJson = strJson.Replace(",\"", "*\"").Replace("\":", "\"#").ToString();
        //取出表名   
        var rg = new Regex(@"(?<={)[^:]+(?=:\[)", RegexOptions.IgnoreCase);
        string strName = rg.Match(strJson).Value;
        DataTable tb = null;
        //去除表名   
        if (strJson.Contains("["))
        {
            strJson = strJson.Substring(strJson.IndexOf("[") + 1);
            strJson = strJson.Substring(0, strJson.IndexOf("]"));
        }
        //获取数据   
        rg = new Regex(@"(?<={)[^}]+(?=})");
        MatchCollection mc = rg.Matches(strJson);
        for (int i = 0; i < mc.Count; i++)
        {
            string strRow = mc[i].Value;
            string[] strRows = strRow.Split('*');

            //创建表   
            if (tb == null)
            {
                tb = new DataTable();
                tb.TableName = strName;
                foreach (string str in strRows)
                {
                    var dc = new DataColumn();
                    string[] strCell = str.Split('#');

                    if (strCell[0].Substring(0, 1) == "\"")
                    {
                        int a = strCell[0].Length;
                        dc.ColumnName = strCell[0].Substring(1, a - 2);
                    }
                    else
                    {
                        dc.ColumnName = strCell[0];
                    }
                    tb.Columns.Add(dc);
                }
                tb.AcceptChanges();
            }

            //增加内容   
            DataRow dr = tb.NewRow();
            for (int r = 0; r < strRows.Length; r++)
            {
                dr[r] = strRows[r].Split('#')[1].Trim().Replace("，", ",").Replace("：", ":").Replace("\"", "");
            }
            tb.Rows.Add(dr);
            tb.AcceptChanges();
        }

        return tb;
    }

    /// <summary>  
    /// 获取主机MAC地址  
    /// </summary>  
    /// <param name="sender"></param>  
     
    public static string GetMac()
    {
        string Mac = "";
        ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration");
        ManagementObjectCollection moc2 = mc.GetInstances();
        foreach (ManagementObject mo in moc2)
        {
            if ((bool)mo["IPEnabled"] == true)
            Mac = mo["MacAddress"].ToString();
            mo.Dispose();
        }
        return Mac;
    }
    ///<summary>
    ///获取主机CPU序列号
    /// </summary>
    public static string GetCpu()
    {
        string cpuInfo = "";//cpu序列号 
        ManagementClass cimobject = new ManagementClass("Win32_Processor");
        ManagementObjectCollection moc = cimobject.GetInstances();
        foreach (ManagementObject mo in moc)
        {
            cpuInfo += mo.Properties["ProcessorId"].Value.ToString();
        }
        return cpuInfo;
    }

    ///<summary>
    ///获取主机硬盘ID
    /// </summary>
    public static string GetHDid()
    {
        string HDid="";
        ManagementClass cimobject1 = new ManagementClass("Win32_DiskDrive");
        ManagementObjectCollection moc1 = cimobject1.GetInstances();
        foreach (ManagementObject mo in moc1)
        {
            HDid += (string)mo.Properties["Model"].Value;
        }
        return HDid;
    }
    /// <summary>
    /// C#端页码条分页方法
    /// </summary>
    /// <param name="pageindex"></param>
    /// <param name="pagesize"></param>
    /// <returns></returns>
    public static string SplitPager(int pageindex, int pagesize, DataTable dt, string keyword, int totalSum)
    {
        keyword = BitConverter.ToString(System.Text.Encoding.UTF8.GetBytes(keyword));
        keyword = "%" + keyword.Replace("-", "%");
        StringBuilder SplitPage = new StringBuilder();
        decimal rc = 0;
        if (dt != null && dt.Rows.Count > 0)
        {
            if (totalSum > 0) { rc = totalSum; }
            else {
                rc = decimal.Parse(dt.Rows[0]["totalRecs"].ToString());//总记录数
            }
            int totalpage = Convert.ToInt32(Math.Ceiling(rc / pagesize).ToString());
            int nextIndex = pageindex + 1;
            int preIndex = pageindex - 1;
            string nextStr = "";
            string preStr = "";
            if (nextIndex > totalpage)
            {
                nextStr = "";
            }
            else
            {
                nextStr = "<a class='hlink' style='padding-right:10px;' href=\"result.aspx?key=" + keyword + "&pg=" + nextIndex + "&pz=" + pagesize + "\"> 下一页 </a>";
            }
            if (pageindex == 1)
            {
                preStr = "";
            }
            else
            {
                preStr = "<a class='hlink' style='padding-right:8px;' href=\"result.aspx?key=" + keyword + "&pg=" + preIndex + "&pz=" + pagesize + "\"> 上一页 </a>";
            }
            SplitPage.Append("<div class=\"scott\">");
            //SplitPage.Append("总记录：" + rc + " 总页数：" + totalpage + " ");
            if (pageindex != 1)
            {
                SplitPage.Append("<a class='hlink' href=\"result.aspx?key=" + keyword + "&pg=1" + "&pz=" + pagesize + "\">首页</a>");
            }
            SplitPage.Append(preStr);
            int Step = 4;
            int LeftNum = 0;
            int RightNum = 0;
            if ((pageindex - Step) < 1)
            {
                LeftNum = 1;
            }
            else
            {
                LeftNum = pageindex - Step;
            }
            if ((pageindex + Step) > totalpage)
            {
                RightNum = totalpage;
            }
            else
            {
                RightNum = pageindex + Step;
            }
            for (int i = LeftNum; i <= RightNum; i++)
            {
                if (i == pageindex)
                {
                    SplitPage.Append("<span class=\"current\">" + i.ToString() + "</span>");
                }
                else
                {
                    SplitPage.Append("<a class='hlink' href=\"result.aspx?key=" + keyword + "&pg=" + i + "&pz=" + pagesize + "\">" + i.ToString() + "</a>");
                }
            }
            SplitPage.Append(nextStr);
            if (pageindex != totalpage)
            {
                SplitPage.Append("<a style='padding-right:8px;' class='hlink' href=\"result.aspx?key=" + keyword + "&pg=" + totalpage + "&pz=" + pagesize + "\">尾页</a>");
            }
            SplitPage.Append("</div>");
        }
        return SplitPage.ToString();
    }

    /// <summary>
    /// 将Base64字符串转换为图片
    /// </summary>
    /// <param name="Base64">图片的Base64编码字符串</param>
    /// <param name="fileStyle">要转换的图片文件格式，如jpg,png等</param>
    /// <param name="w">转换后图片的宽度(单位像素)</param>
    /// <param name="h">转换后图片的高度(单位像素)</param>
    public static string Base64ToImage(string Base64, string fileStyle,int w,int h,string imgPath)
    {
        byte[] bytes = Convert.FromBase64String(Base64);
        MemoryStream memStream = new MemoryStream(bytes);
        System.Drawing.Image image = System.Drawing.Image.FromStream(memStream);
        System.Drawing.Bitmap bmp = new System.Drawing.Bitmap(w, h);//设定照片宽为100像素，高为120像素
        System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(bmp);
        g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
        g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
        g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
        System.Drawing.Rectangle rectDestination = new System.Drawing.Rectangle(0, 0, w, h);
        g.DrawImage(image, rectDestination, 0, 0, image.Width, image.Height, System.Drawing.GraphicsUnit.Pixel);

        string fName = DateTime.Now.ToString("yyyyMMddHHmmssfff");
        if(fileStyle.Contains("."))
        {
            fileStyle = fileStyle.Replace(".","");
        }
        string NewPath = System.Web.HttpContext.Current.Server.MapPath(imgPath);
        bmp.Save(NewPath + fName + "."+ fileStyle);
        bmp.Dispose();
        string photoUrl = imgPath + fName;
        return photoUrl;
    }
    public static string ImgToBase64(string Imagefilename)
    {
        string Base64Str = "";
        try
        {
            System.Drawing.Bitmap bmp = new System.Drawing.Bitmap(Imagefilename);            
            FileStream fs = new FileStream(Imagefilename + ".txt", FileMode.Create);
            StreamWriter sw = new StreamWriter(fs);

            MemoryStream ms = new MemoryStream();
            bmp.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
            byte[] arr = new byte[ms.Length];
            ms.Position = 0;
            ms.Read(arr, 0, (int)ms.Length);
            ms.Close();
            String strbaser64 = Convert.ToBase64String(arr);
            Base64Str = strbaser64;
            sw.Close();
            fs.Close();
        }
        catch (Exception ex)
        {
            throw ex;
        }
        return Base64Str;
    }
    ///<summary>
    ///生成订单流水号
    /// </summary>
    public static string GetOrderNo()
    {
        string Number = DateTime.Now.ToString("yyMMddHHmmss");//yyyyMMddHHmmssms
        return Number + Next(1000, 1).ToString();
    }
    private static int Next(int numSeeds, int length)
    {
        // Create a byte array to hold the random value.  
        byte[] buffer = new byte[length];
        // Create a new instance of the RNGCryptoServiceProvider.  
        System.Security.Cryptography.RNGCryptoServiceProvider Gen = new System.Security.Cryptography.RNGCryptoServiceProvider();
        // Fill the array with a random value.  
        Gen.GetBytes(buffer);
        // Convert the byte to an uint value to make the modulus operation easier.  
        uint randomResult = 0x0;//这里用uint作为生成的随机数  
        for (int i = 0; i < length; i++)
        {
            randomResult |= ((uint)buffer[i] << ((length - 1 - i) * 8));
        }
        // Return the random number mod the number  
        // of sides. The possible values are zero-based  
        return (int)(randomResult % numSeeds);
    }
}
